package org.xhy.retryerboot.proxy;

import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import org.xhy.retryer.core.Retryer;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.Set;

/**
 * @description:
 * @gitee: https://gitee.com/XhyQAQ
 * @copyright: B站: https://space.bilibili.com/152686439
 * @Author: Xhy
 * @CreateTime: 2024-05-01 00:12
 */
public class RetryerProxy implements MethodInterceptor {
    private  Object target;

    private  Map<Integer,Retryer> retryerHashMap;

    public RetryerProxy() {

    }

    public RetryerProxy(Object target,Map<Integer,Retryer> retryerHashMap) {
        this.target = target;
        this.retryerHashMap = retryerHashMap;
    }


    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        final int hashCode = method.hashCode();
        if (retryerHashMap.containsKey(hashCode)){
            return retryerHashMap.get(hashCode).exec(()->{
                final Object o1;
                try {
                    o1 = methodProxy.invokeSuper(o, objects);
                } catch (Throwable e) {
                    throw new RuntimeException(e);
                }
                return o1;
            });
        }
        return methodProxy.invokeSuper(o,objects);
    }
}
